//
//  XS_DownloadStartVC.swift
//  XueDao
//
//  Created by Mac on 2020/12/29.
//

import UIKit
import AliyunMediaDownloader

class XS_DownloadStartVC: XS_BaseVC {
    
    //下载要用的
    lazy var bottomView : XS_DownloadStartBottomView = {
        let bottomView = XS_DownloadStartBottomView.init(frame: CGRect.init(x: 0, y: .screenHeight - .bottomHeight - 49 - .barHeight - 44, width: .screenWidth, height: 49 + .bottomHeight))
        bottomView.delegate = self
        return bottomView
    }()
    
    var id = ""
    var curriculumModel = XS_KCcurriculumM()
    
    lazy var models: [XS_KCqueryHoursM] = []
    
    //本地数据要用的
    var downloadModel = XS_DownloadModel()
    
    var foldDataArray = [Bool]()

    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        for i in 0...100 {
            foldDataArray.append(false)
        }

        // Do any additional setup after loading the view.
        shouldNavBarHidden = false
        tableView.register(UINib.init(nibName: "XS_DownloadStartListCell", bundle: Bundle.main), forCellReuseIdentifier: "XS_DownloadStartListCell")
        tableView.register(UINib.init(nibName: "XS_DownloadStartHeaderView", bundle: Bundle.main), forHeaderFooterViewReuseIdentifier: "XS_DownloadStartHeaderView")
        if title != "选择下载" {
            let rightItem = UIBarButtonItem.init(title: "管理", style: .plain, target: self, action: #selector(manageBtnAction))
            rightItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor : UIColor.qmui_color(withHexString: "333333")!], for: .normal)
            navigationItem.rightBarButtonItem = rightItem
            reloadLocalData()
            
            NotificationCenter.default.addObserver(self, selector: #selector(updateDownloadingQueue), name: NSNotification.Name.init(.downloadingQueueUpdateNotification), object: nil)
            
        }else{
            tableView.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: bottomView.qmui_height, right: 0)
            bottomView.type = .download
            view.addSubview(bottomView)
            XS_DownloadManager.shared.delegate = self
            requestData()
        }
    }
    
    @objc func updateDownloadingQueue(){
        let doneArray = XS_DownloadManager.shared.getModels()
        
        for subModel in doneArray {
            if subModel.curriculumModel.id == downloadModel.curriculumModel.id {
                downloadModel = subModel
                reloadLocalData()
                break
            }
        }
    }
    
    func reloadLocalData(){
        self.models = downloadModel.hourModels
        let view = Bundle.main.loadNibNamed("XS_DownloadFooterView", owner: nil, options: nil)?.last as! XS_DownloadFooterView
        let filePath = XS_DownloadManager_CourseFilePath
        let fileSize = filePath.getFileSize()
        let freeSize = XS_DownloadManager.shared.getSystemFreeSize()
        view.titleLabel.text = String.init(format: "已下载课件%ldM ,可用空间%ldG", fileSize/1024/1024,freeSize/1024/1024/1024)
        tableView.tableFooterView = view
        self.tableView.reloadData()
    }
    
    func requestData(){
        let point = CGPoint(x: .screenWidth/2.0 + 20, y: .screenHeight/2.0)
        view.isUserInteractionEnabled = false
        view.makeToastActivity(point)
        XS_NetWork.requestJson("/hour/queryDownloadHours", parameters: ["id":id])
            .mapModels(type: XS_KCqueryHoursM.self)
            .subscribe(onNext: { [weak self] models, resp in
                self?.view.isUserInteractionEnabled = true
                self?.view.hideToastActivity()
                guard let `self` = self else { return }
                self.models = models
                //查找本地文件，看看是否可以下载
                for sectionModel in models{
                    for rowModel in sectionModel.curriculumHourDtoList {
                        for dirPath in XS_DownloadManager.shared.getAllFile(filePath: XS_DownloadManager_CourseFilePath){
                            let newDirPath = NSHomeDirectory() + "/Documents/Courses" + "/" + dirPath
                            for filePath in XS_DownloadManager.shared.getAllFile(filePath: newDirPath) {
                                if filePath.contains(rowModel.curriculumHourName) {
                                    //下载完成了
                                    rowModel.filePath = filePath
                                    rowModel.progress = 100
                                }
                            }
                            
                        }
                    }
                }
                self.tableView.reloadData()
            }).disposed(by: disposeBag)
    }
    
    @objc func manageBtnAction(){
        if navigationItem.rightBarButtonItem?.title == "管理" {
            let rightItem = UIBarButtonItem.init(title: "完成", style: .plain, target: self, action: #selector(manageBtnAction))
            rightItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor : UIColor.qmui_color(withHexString: "333333")!], for: .normal)
            navigationItem.rightBarButtonItem = rightItem
            //显示删除BottomView
            bottomView.type = .manage
            view.addSubview(bottomView)
            tableView.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: bottomView.qmui_height, right: 0)
            for sectionModel in models {
                for rowModel in sectionModel.curriculumHourDtoList {
                    rowModel.selected = false
                    rowModel.isManage = true
                }
            }
            tableView.reloadData()
        }else{
            let rightItem = UIBarButtonItem.init(title: "管理", style: .plain, target: self, action: #selector(manageBtnAction))
            rightItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor : UIColor.qmui_color(withHexString: "333333")!], for: .normal)
            navigationItem.rightBarButtonItem = rightItem
            //隐藏删除BottomView
            bottomView.removeFromSuperview()
            tableView.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)
            for sectionModel in models {
                for rowModel in sectionModel.curriculumHourDtoList {
                    rowModel.selected = false
                    rowModel.isManage = false
                }
            }
            tableView.reloadData()
        }
    }
}

extension XS_DownloadStartVC : UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        if title != "选择下载" {
            var sectionCount = 0
            for sectionModel in models {
                var rowCount = 0
                for rowModel in sectionModel.curriculumHourDtoList {
                    if rowModel.progress == 100 {
                        rowCount = rowCount + 1
                    }
                }
                if rowCount > 0 {
                    sectionCount = sectionCount + 1
                }
            }
            return sectionCount
        }
        return models.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let model = models[section]
        let ret = foldDataArray[section]
        return ret ? 0 : model.curriculumHourDtoList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "XS_DownloadStartListCell", for: indexPath) as! XS_DownloadStartListCell
        if models.count > 0 {
            let model = models[indexPath.section]
            cell.model = model.curriculumHourDtoList[indexPath.row]
        }
        cell.canDownload = (title == "选择下载")
        cell.delegate = self
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if title != "选择下载" {
            let sectionModel = models[indexPath.section]
            let rowModel = sectionModel.curriculumHourDtoList[indexPath.row]
            return XS_DownloadStartListCell.getCellHeight(model: rowModel)
        }else{
            return 64
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = Bundle.main.loadNibNamed("XS_DownloadStartHeaderView", owner: nil, options: nil)?.last as! XS_DownloadStartHeaderView
        headerView.delegate = self
        headerView.section = section
        let model = models[section]
        headerView.model = model
        if title == "选择下载" {
            headerView.numberBtn.setTitle("共"+String(model.curriculumHourDtoList.count)+"讲", for: .normal)
        }else{
            var count = 0
            for courseModel in model.curriculumHourDtoList {
                if courseModel.progress == 100 {
                    count = count + 1
                }
            }
            headerView.numberBtn.setTitle("共"+String(count)+"讲", for: .normal)
        }
        return headerView
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 54
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if title != "选择下载" {
            let chapterModel = models[indexPath.section]
            let model = chapterModel.curriculumHourDtoList[indexPath.row]
            
            let vc = XS_VideoFullVC()
            vc.playerUrl = URL(fileURLWithPath: model.filePath)
            present(vc, animated: true, completion: nil)
        }
    }
}

extension XS_DownloadStartVC : XS_DownloadStartHeaderViewDelegate{
    func headerView(headerView: XS_DownloadStartHeaderView, didClickFoldBtn: QMUIButton) {
        didClickFoldBtn.isSelected = !didClickFoldBtn.isSelected
        headerView.model.selected = didClickFoldBtn.isSelected
        foldDataArray[headerView.section] = didClickFoldBtn.isSelected
        tableView.reloadData()
    }
}

extension XS_DownloadStartVC : XS_DownloadStartListCellDelegate{
    func listCell(listCell: XS_DownloadStartListCell, didClickSelectBtn: UIButton) {
        didClickSelectBtn.isSelected = !didClickSelectBtn.isSelected
        listCell.model.selected = didClickSelectBtn.isSelected
        
        tableView.reloadData()
        var count = 0
        for chapterModel in models {
            for courseModel in chapterModel.curriculumHourDtoList {
                if courseModel.selected {
                    if title != "选择下载" {
                        if courseModel.progress == 100 && courseModel.filePath.count > 0 {
                            count = count + 1
                        }
                    }else{
                        if courseModel.progress == 0 {
                            count = count + 1
                        }
                    }
                }
            }
        }
        if count > 0 {
            bottomView.allBtn.setTitle(String.init(format: "已选%d节", count), for: .normal)
            bottomView.allBtn.isSelected = true
        }else{
            bottomView.allBtn.isSelected = false
            bottomView.allBtn.setTitle("已选择0节", for: .normal)
        }
    }
}

extension XS_DownloadStartVC : XS_DownloadStartBottomViewDelegate{
    func bottomView(bottomView: XS_DownloadStartBottomView, didClickOperateBtn: UIButton) {
        if didClickOperateBtn.titleLabel?.text == "下载" {
            //下载操作
            var count = 0
            for chapterModel in models {
                for courseModel in chapterModel.curriculumHourDtoList {
                    if title != "选择下载" {
                        if courseModel.progress == 100 {
                            count = count + 1
                        }
                    }else{
                        if courseModel.progress == 0 {
                            count = count + 1
                        }
                    }
                }
            }
            if count > 0 {
                view.makeToast("开始下载")
            }else{
                view.makeToast("未选择任何课程")
            }
            for chapterModel in models {
                for courseModel in chapterModel.curriculumHourDtoList {
                    if courseModel.selected && courseModel.progress == 0 {
                        courseModel.isDownloading = 1;
                        let downloadModel = XS_DownloadModel()
                        downloadModel.curriculumModel = curriculumModel
                        downloadModel.hourModels = models
                        downloadModel.hourModel = chapterModel
                        downloadModel.listModel = courseModel
                        XS_DownloadManager.shared.download(downloadModel: downloadModel)
                    }
                }
            }
        }else if didClickOperateBtn.titleLabel?.text == "删除"{
            //删除操作
            let models = downloadModel.hourModels
            var allCount = 0
            var selectCount = 0
            for chapterModel in models{
                for courseModel in chapterModel.curriculumHourDtoList {
                    if courseModel.progress == 100 {
                        allCount = allCount + 1
                        if courseModel.selected && courseModel.progress == 100 {
                            selectCount = selectCount + 1
                            XS_DownloadManager.shared.removeFile(model: courseModel)
                        }
                    }
                }
            }
            //删除model
            if allCount == selectCount {
                navigationController?.popViewController(animated: true)
            }else{
                let dataArray = XS_DownloadManager.shared.getModels()
                for subModel in dataArray {
                    if subModel.curriculumModel.id == downloadModel.curriculumModel.id{
                        downloadModel = subModel
                        break
                    }
                }
                self.models = downloadModel.hourModels
                for sectionModel in self.models {
                    for rowModel in sectionModel.curriculumHourDtoList {
                        rowModel.selected = false
                        rowModel.isManage = true
                    }
                }
                tableView.reloadData()
            }
        }
    }
    
    func bottomView(bottomView: XS_DownloadStartBottomView, didClickAllBtn: QMUIButton) {
        for chapterModel in models {
            for courseModel in chapterModel.curriculumHourDtoList {
                if title == "选择下载" {
                    if courseModel.progress == 0 {
                        courseModel.selected = didClickAllBtn.isSelected
                    }
                }else{
                    courseModel.selected = didClickAllBtn.isSelected
                }
            }
        }
        
        var count = 0
        for chapterModel in models {
            for courseModel in chapterModel.curriculumHourDtoList {
                if courseModel.selected {
                    if title == "选择下载" {
                        if courseModel.progress == 0{
                            count = count + 1
                        }
                    }else{
                        if courseModel.progress == 100{
                            count = count + 1
                        }
                    }
                    
                }
            }
        }
        
        if count > 0 {
            bottomView.allBtn.setTitle(String.init(format: "已选%d节", count), for: .normal)
            bottomView.allBtn.isSelected = true
        }else{
            bottomView.allBtn.isSelected = false
            bottomView.allBtn.setTitle("已选择0节", for: .normal)
        }
        
        tableView.reloadData()
    }
}

extension XS_DownloadStartVC : XS_DownloadManagerDelegate{
    func downloadManager(downloadManager: XS_DownloadManager, downloader: AliMediaDownloader, didError: AVPErrorModel) {
        //下载失败
        view.makeToast(didError.message)
    }
    
    func downloadManager(downloadManager: XS_DownloadManager, downloader: AliMediaDownloader, didProgress: Int32) {
        //加载进度信息
        if models.count > 0 {
            for index in 0...models.count - 1 {
                let chapterModel = models[index]
                for jndex in 0...chapterModel.curriculumHourDtoList.count - 1 {
                    let courseModel = chapterModel.curriculumHourDtoList[jndex]
                    if downloadManager.currentModel?.listModel.id == courseModel.id {
                        courseModel.progress = didProgress
                        courseModel.selected = false
                        self.tableView.reloadItemsAtIndexPaths([IndexPath.init(row: jndex, section: index)], animationStyle: .none)
                    }
                }
            }
        }
    }
    
    func downloadManager(downloadManager: XS_DownloadManager, downloader: AliMediaDownloader, didComplete: Bool) {
        //下载完成
        if models.count > 0 {
            for index in 0...models.count - 1 {
                let chapterModel = models[index]
                for jndex in 0...chapterModel.curriculumHourDtoList.count - 1 {
                    let courseModel = chapterModel.curriculumHourDtoList[jndex]
                    if downloadManager.currentModel?.listModel.id == courseModel.id {
                        courseModel.progress = 100
                        courseModel.selected = false
                        self.tableView.reloadItemsAtIndexPaths([IndexPath.init(row: jndex, section: index)], animationStyle: .none)
                    }
                }
            }
        }
    }
}
